package com.jzo2o.customer.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.model.dto.PageQueryDTO;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.mapper.ConsumerAddressMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.ConsumerAddressService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageHelperUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.tomcat.jni.Address;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-04
 */
@Service
@Slf4j
public class ConsumerAddressServiceImpl extends ServiceImpl<ConsumerAddressMapper, AddressBook> implements ConsumerAddressService {

    @Resource
    private ConsumerAddressMapper consumerAddressMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public PageResult<AddressBook> findByPage(AddressBookPageQueryReqDTO dto) {
        //参数校验
        if(ObjectUtils.isEmpty(dto)){
            throw new CommonException("查询参数异常，不能为空");
        }
        if(dto.getPageNo() <=0 && dto.getPageSize() <=0){
            throw new CommonException("查询参数异常");
        }
        //获取当前用户id
        Long currentUserId = UserContext.currentUserId();
        log.info("当前操作用户id为:{}", currentUserId);
        //分页查询
        return PageHelperUtils.selectPage(dto,
                () -> consumerAddressMapper.queryByCurrentUserId(currentUserId));
    }

    @Override
    public void add(AddressBookUpsertReqDTO dto) {
        if(ObjectUtils.isEmpty(dto)){
            throw new CommonException("新增参数异常，不能为空");
        }
        //数据处理
        //如果添加的地址被选择为默认地址
        if(Objects.equals(dto.getIsDefault(), NumberUtils.INTEGER_ONE)){
            //需要去除当前默认地址
            this.lambdaUpdate().eq(AddressBook::getUserId, UserContext.currentUserId())
                    .eq(AddressBook::getIsDefault, NumberUtils.INTEGER_ONE)
                    .set(AddressBook::getIsDefault, NumberUtils.INTEGER_ZERO).update();
        }
        //获取local中的经纬度
        String[] split = dto.getLocation().split(",");
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(dto, addressBook);
        addressBook.setUserId(UserContext.currentUserId());
        addressBook.setLon(NumberUtils.createDouble(split[0]));
        addressBook.setLat(NumberUtils.createDouble(split[1]));
        //业务处理
        save(addressBook);
    }

    /**
     * 根据地址id查询地址详情
     * @param addressBookId
     */
    @Override
    public AddressBook findById(Long addressBookId) {
        if(addressBookId == null){
            throw new CommonException("查询参数异常，地址id不能为空");
        }
        AddressBook address = this.getById(addressBookId);
        if(address == null){
            throw new CommonException("查询参数异常，地址不存在");
        }
        return address;
    }

    /**
     * 设置默认地址
     * @param addressBookId
     * @param flag
     */
    @Override
    public void setDefaultAddress(Long addressBookId, Integer flag) {
        //参数校验
        if(addressBookId == null || flag == null){
            throw new CommonException("查询参数异常，地址id不能为空");
        }
        //查询当前用户是否有默认地址
        AddressBook addressBook = this.lambdaQuery()
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .eq(AddressBook::getIsDefault, flag).one();
        if(!ObjectUtils.isEmpty(addressBook)){
          //当前存在一个默认地址，需要将原有的默认地址取消默认
            this.lambdaUpdate().eq(AddressBook::getId, addressBook.getId())
                    .set(AddressBook::getIsDefault, NumberUtils.INTEGER_ZERO).update();
        }
        //业务处理
        this.lambdaUpdate()
                .eq(AddressBook::getId, addressBookId)
                .set(AddressBook::getIsDefault, flag)
                .update();
    }

    @Override
    public void update(Long addressBookId, AddressBookUpsertReqDTO dto) {
        if(addressBookId == null || ObjectUtils.isEmpty(dto)){
            throw new CommonException("更新传入参数异常");
        }
        //判断id对应的地址是否存在
        if(ObjectUtils.isEmpty(this.getById(addressBookId))){
            throw new CommonException("数据地址主键有误，地址不存在");
        }
        //如果更新的地址被选择为默认地址
        if(Objects.equals(dto.getIsDefault(), NumberUtils.INTEGER_ONE)){
            //需要去除当前默认地址
            this.lambdaUpdate().eq(AddressBook::getUserId, UserContext.currentUserId())
                    .eq(AddressBook::getIsDefault, NumberUtils.INTEGER_ONE)
                    .set(AddressBook::getIsDefault, NumberUtils.INTEGER_ZERO).update();
        }
        //数据处理
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(dto, addressBook);
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBook.setUpdateBy(UserContext.currentUserId());
        addressBookMapper.update(addressBook, new LambdaQueryWrapper<AddressBook>().eq(AddressBook::getId, addressBookId));
    }

    /**
     * 批量删除地址信息
     * @param ids
     */
    @Override
    public void batchDelete(List<Long> ids) {
        if(CollectionUtils.isEmpty(ids)){
            throw new CommonException("请选择你需要参数的地址");
        }
        //判断地址都是否存在
        ids.forEach(id->
        {
            Long a = addressBookMapper.selectById(id);
            if(ObjectUtils.isEmpty(a) ){
                throw new CommonException(id + "数据地址主键有误，地址不存在");
            }
        });

        Long l = addressBookMapper.batchDeleteAddress(ids);
        if(l <= 0){
            throw new CommonException("删除失败");
        }
    }
}
